package org.linlinjava.litemall.admin.service;

import org.apache.commons.lang3.StringUtils;
import org.linlinjava.litemall.db.dao.LitemallOrderGoodsMapper;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.service.LitemallBillService;
import org.linlinjava.litemall.db.service.LitemallBrandService;
import org.linlinjava.litemall.db.service.LitemallCustomerService;
import org.linlinjava.litemall.admin.util.BillConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.print.DocFlavor;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Random;

/**
 * @author: weilai
 * @date: 2019/12/12
 * @description:
 */

@Service
public class AdminBillService {
   @Autowired
    private BrandInvoiceService brandInvoiceService;
    @Autowired
    private LitemallBillService billService;
    @Autowired
    private LitemallBrandService brandService;
    @Autowired
    private LitemallCustomerService litemallCustomerService;
    @Resource
    private LitemallOrderGoodsMapper orderGoodsMapper;


    //未支付： 101生成 102手动取消 103，超时自动取消 支付：： 201未确定。202 已确定 203 自动确定

    /**
     * 平台抽成和商家收入比率  1 : RATE_SL 霜林科技的抽成比例   2 :RATE_COMPANY  给公司的抽成比例
     */
    private static final String RATE_SL = String.valueOf(0.15);
    private static final String RATE_COMPANY = String.valueOf(0.85);

    private BigDecimal platformRate = new BigDecimal(RATE_SL);
    private BigDecimal brandRate = new BigDecimal(RATE_COMPANY);

    private BigDecimal bigDecimalZero =  new BigDecimal("0");

    /**
     * 详情4：：如果有黄牛:::更新相关：：。黄牛的收入=霜林的收入 * 给黄牛的比例(0-100之间 )
     * @param billId
     * @param scalperRateBigDecimal
     * @return
     */
    public Object updateBill4ScalperRate(Integer billId,BigDecimal scalperRateBigDecimal){
        //前台决定中间商的比率。更新：：upScalper//0.5就是黄牛抽成比例50%

        LitemallBill bill = billService.findById(billId);
        //实际收入
        BigDecimal actualPrice = bill.getActualPrice();
        //霜林收入 = 实际收入的 * 霜林收入比 (platformRate)
        BigDecimal actualPrice4PlatformRate = actualPrice.multiply(platformRate);
        //黄牛收入 ==（平台的收入）*黄牛的比率
        BigDecimal scalperIncome = actualPrice4PlatformRate.multiply(scalperRateBigDecimal);

        bill.setScalperPrice(scalperIncome);
        //现在的收入==之前（已经减去优惠金额，现在只需要减去黄牛）
        bill.setIncome(bill.getIncome().subtract(scalperIncome));
        //更改标识为有黄牛
        bill.setHasScalper(1);
        billService.updateBill(bill);
        return bill;
    }


    /**
     * 1订单order中complete完结订单状态200时 才 创建与霜林科技结算单bill    2 add一个对账单  同时创建一个霜林给商户的票据信息
     * @param order
     * @return
     */
    public Object create(LitemallOrder order){
        //如果有问题。可以改为：：先拿到订单ID。 找打订单再去创建结算单
        //拿到订单数据  并且插入bill
        LitemallBill bill = new LitemallBill();
        Integer brandId = order.getBrandId();
        String brandName = brandService.findById(brandId).getName();
        //11结算单号码。可能不需要
        bill.setNum(generateBillNum());
        //1订单编号OrderSn  //2订单ID,OrderId ;//3商户名。orderService有方法  //4商户ID
        bill.setOrderSn(order.getOrderSn());
        bill.setOrderId(order.getId());
        bill.setBrandName(brandName);
        bill.setBrandId(brandId);
        //订单确认时间
        bill.setOrderConfirmTime(order.getConfirmTime());
        //5账单单添加时间
        bill.setAddTime(LocalDate.now());
        //6客户  应支付：订单总金额(不是实际付款。订单金额中没有钱，需要去orderGoods中FF。）
        bill.setOrderPrice(goodsTotalPrice(order));

        //7平台优惠(详情3) 如果没有优惠默认是0
        if(order.getCouponPrice().signum()<=0){
            bill.setCouponPrice(bigDecimalZero);
        }else {
            bill.setCouponPrice(order.getCouponPrice());
        }

        //8商家优惠金额
        if(brandCouponPrice(order).signum()<=0){
            bill.setBrandCoupon(bigDecimalZero);
        }else {
            bill.setBrandCoupon(brandCouponPrice(order));
        }

        //9实际支付金额（详情6：商户应该开票=商户实际收入+平台收入）
        if (order.getActualPrice().signum()<=0){
            bill.setActualPrice(bigDecimalZero);
        }else {
            bill.setActualPrice(order.getActualPrice());
        }
        //10点击添加就会设置状态101为未支付
        bill.setStatus(BillConstant.STATUS_CREATE);

        //详情1：平台向商户开票金额 = 实付金额*15%
        if(invoicePrice2brand(order).signum()<=0){
            bill.setInvoicePrice(bigDecimalZero);
        }else {
            bill.setInvoicePrice(invoicePrice2brand(order));
        }
        //详情2：商户收入金额=实付金额*85%
        if (brandIncome(order).signum()<=0){
            bill.setBrandIncome(bigDecimalZero);
        }else {
            bill.setBrandIncome(brandIncome(order));
        }
        //增加中介的邀请码
        bill.setCustomerInvitation(invitationByOrder(order));
        //详情4：黄牛收入 （实际收入*15%）*50%  .默认黄牛为0。
         bill.setScalperPrice(bigDecimalZero);
        //详情5默认：平台收入=实付金额*15%-平台优惠       //没有有黄牛：：： 否则---黄牛收入
        bill.setIncome(invoicePrice2brand(order).subtract(order.getCouponPrice()));
        //创建一个商户票据单（数据来自bill）
        LitemallBrandInvoice brandInvoice = brandInvoiceService.create(bill);
        //保存票据InvoiceId .到bill中
        bill.setInvoiceId(brandInvoice.getId());
        //保存到数据库
        billService.create(bill);
        return bill;
    }




    //d根据订单获取  中介的邀请码
    public String invitationByOrder(LitemallOrder litemallOrder){
        int userId = litemallOrder.getUserId();
        LitemallCustomer user = litemallCustomerService.getUser((long) userId);
        String  invitation= user.getInvitation();
        if (StringUtils.isEmpty(invitation)){
            return "";
        }
       return invitation;
    }



    /**
     * 商家优惠的金额=订单金额-平台优惠价格-实际支付价格
     * @param litemallOrder
     * @return
     */
    public BigDecimal brandCouponPrice(LitemallOrder litemallOrder){
        //订单本来的金额
        BigDecimal orderPrice = litemallOrder.getOrderPrice();
        //平台优惠券
        BigDecimal couponPrice = litemallOrder.getCouponPrice();
        //实际支付的金额
        BigDecimal actualPrice = litemallOrder.getActualPrice();
        if (orderPrice.signum()<=0){
            orderPrice = bigDecimalZero;
        }
        if (couponPrice.signum()<=0){
            couponPrice = bigDecimalZero;
        }
        if (actualPrice.signum()<=0){
            actualPrice = bigDecimalZero;
        }
        return (orderPrice.subtract(actualPrice)).subtract(couponPrice);

    }

    /**
     *详情1： platform平台向brand商家开票金额=实际支付价格*15%
     * @param litemallOrder
     * @return
     */
    public BigDecimal invoicePrice2brand(LitemallOrder litemallOrder){
        BigDecimal orderActualPrice = litemallOrder.getActualPrice();//订单实际支付的金额
        if (orderActualPrice.signum()<=0){
            orderActualPrice = bigDecimalZero;
        }

        BigDecimal invoice2brand = orderActualPrice.multiply(platformRate);
        return invoice2brand;
    }

    /**
     * 详情2：商户收入金额=实际支付金额*85%
     * @param litemallOrder
     * @return
     */
    public BigDecimal brandIncome(LitemallOrder litemallOrder){
        //订单实际支付的金额
        BigDecimal orderActualPrice = litemallOrder.getActualPrice();
        if (orderActualPrice.signum()<=0){
            orderActualPrice = bigDecimalZero;
        }
        BigDecimal brandIncome4ActualPrice = orderActualPrice.multiply(brandRate);//
        return brandIncome4ActualPrice;
    }

    //6商品的总价：订单应该支付总金额(订单金额中没有钱，需要去orderGoods中。)
    public BigDecimal goodsTotalPrice(LitemallOrder litemallOrder){
       Integer orderId= litemallOrder.getId();
        LitemallOrderGoodsExample example = new LitemallOrderGoodsExample();
        example.or().andOrderIdEqualTo(orderId).andDeletedEqualTo(false);

        List<LitemallOrderGoods> litemallOrderGoods = orderGoodsMapper.selectByExample(example);

        BigDecimal totalPrice = new BigDecimal(0);
        for (LitemallOrderGoods orderGoods : litemallOrderGoods) {
            totalPrice= totalPrice.add(orderGoods.getGoodsPrice());
        }
        return totalPrice;
    }
    //生成   随机数
    private String getRandomNum(Integer num) {
        String base = "0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < num; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }
    //生成   结算单   唯一ID
    public String generateBillNum() {
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyyMMdd");
        String now = df.format(LocalDate.now());
        String billNum = now + getRandomNum(6);
        return billNum;
    }
    //bigDecimal::: setScale(2, RoundingMode.HALF_UP);//保留两位小数
}
